USE [msdb]
GO

/****** Object:  Job [VDBA - Failed Jobs]    Script Date: 1/14/2015 12:00:32 PM ******/
IF EXISTS (SELECT name FROM msdb.dbo.syscategories WHERE name=N'VDBA' AND category_class=1)
EXEC msdb.dbo.sp_delete_job @job_id=N'4ba7e04b-141d-4702-b92d-d222fedb8336', @delete_unused_schedule=1
GO

/****** Object:  Job [VDBA - Failed Jobs]    Script Date: 1/14/2015 12:00:32 PM ******/
BEGIN TRANSACTION
DECLARE @ReturnCode INT
SELECT @ReturnCode = 0
/****** Object:  JobCategory [VDBA]    Script Date: 1/14/2015 12:00:32 PM ******/
IF NOT EXISTS (SELECT name FROM msdb.dbo.syscategories WHERE name=N'VDBA' AND category_class=1)
BEGIN
EXEC @ReturnCode = msdb.dbo.sp_add_category @class=N'JOB', @type=N'LOCAL', @name=N'VDBA'
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback

END

DECLARE @jobId BINARY(16)
EXEC @ReturnCode =  msdb.dbo.sp_add_job @job_name=N'VDBA - Failed Jobs', 
		@enabled=1, 
		@notify_level_eventlog=0, 
		@notify_level_email=0, 
		@notify_level_netsend=0, 
		@notify_level_page=0, 
		@delete_level=0, 
		@description=N'Periodic report on jobs in a failed state.', 
		@category_name=N'VDBA', 
		@owner_login_name=N'sa', @job_id = @jobId OUTPUT
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
/****** Object:  Step [Create Report File]    Script Date: 1/14/2015 12:00:32 PM ******/
EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'Create Report File', 
		@step_id=1, 
		@cmdexec_success_code=0, 
		@on_success_action=1, 
		@on_success_step_id=0, 
		@on_fail_action=2, 
		@on_fail_step_id=0, 
		@retry_attempts=0, 
		@retry_interval=0, 
		@os_run_priority=0, @subsystem=N'CmdExec', 
		@command=N'sqlcmd -E -S$(ESCAPE_SQUOTE(SRVR))  -l30 -h-1 -w300 -W -b -dmaster -Q" Exec master.dbo.VDBA_FailedJobs @Rpt_JobID = $(ESCAPE_NONE(JOBID)) " -t600 -o C:\VDBA4\tmp\VDBA_FailedJobAlert.txt', 
		@flags=32
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_update_job @job_id = @jobId, @start_step_id = 1
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_add_jobschedule @job_id=@jobId, @name=N'VDBA Failed jobs check', 
		@enabled=1, 
		@freq_type=4, 
		@freq_interval=1, 
		@freq_subday_type=4, 
		@freq_subday_interval=10, 
		@freq_relative_interval=0, 
		@freq_recurrence_factor=0, 
		@active_start_date=20120416, 
		@active_end_date=99991231, 
		@active_start_time=30200, 
		@active_end_time=30159, 
		@schedule_uid=N'a93263d0-55a9-44d4-a680-b99107a3b1a8'
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_add_jobserver @job_id = @jobId, @server_name = N'(local)'
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
COMMIT TRANSACTION
GOTO EndSave
QuitWithRollback:
    IF (@@TRANCOUNT > 0) ROLLBACK TRANSACTION
EndSave:

GO


